package com.example.demo.controller;

import com.example.demo.commom.Result;
import com.example.demo.entity.Book;
import com.example.demo.service.BookService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/book")
public class BookController {

    @Resource
    private BookService bookService;

    @PostMapping
    public Result<?> save(@RequestBody Book book) {
        int result = bookService.insert(book);
        return result > 0 ? Result.success() : Result.error("400", "保存失败");
    }

    @PutMapping
    public Result<?> update(@RequestBody Book book) {
        int result = bookService.updateById(book);
        return result > 0 ? Result.success() : Result.error("400", "更新失败");
    }

    @PostMapping("/deleteBatch")
    public Result<?> deleteBatch(@RequestBody List<Integer> ids) {
        int result = bookService.deleteBatchIds(ids);
        return result > 0 ? Result.success() : Result.error("400", "批量删除失败");
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        int result = bookService.deleteById(id);
        return result > 0 ? Result.success() : Result.error("400", "删除失败");
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search1,
                              @RequestParam(defaultValue = "") String search2,
                              @RequestParam(defaultValue = "") String search3) {
        List<Book> books = bookService.selectPage(pageNum, pageSize, search1, search2, search3);
        int total = bookService.selectCount(search1, search2, search3);

        Map<String, Object> result = new HashMap<>();
        result.put("records", books);
        result.put("total", total);
        result.put("current", pageNum);
        result.put("size", pageSize);

        return Result.success(result);
    }
}
//这是一个典型的基于Spring Boot和MyBatis-Plus的CRUD控制器。
//
//它通过简洁的代码实现了图书的增删改查功能，并支持分页和多条件查询。
//
//通过统一的返回格式和RESTful风格设计，提高了代码的可维护性和可读性。